package cc.customer.saleHelp.services.Impl;

import cc.customer.expCustomer.dao.ExEmpMapper;
import cc.customer.expCustomer.domain.ExEmp;
import cc.customer.expCustomer.services.ExEmpServices;
import cc.customer.aiEmport.damain.CAiEmp;
import cc.customer.aiEmport.services.AiEmpServices;
import cc.customer.bigEmport.damain.BigEmp;
import cc.customer.bigEmport.dao.BigEmpMapper;
import cc.customer.bigEmport.services.BigEmpServices;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import cc.customer.common.utils.Utils;
import cc.customer.myCustomer.damain.MyCustomer;
import cc.customer.myCustomer.dao.MyCustomerMapper;
import cc.customer.myCustomer.services.CustomeForMy;
import cc.customer.onschool.dao.OnSchoolResourceMapper;
import cc.customer.onschool.domain.OnSchoolResource;
import cc.customer.onschool.services.OnSchoolService;
import cc.customer.saleHelp.dao.CSaleCustomerMapper;
import cc.customer.saleHelp.dao.CsalePlanMapper;
import cc.customer.saleHelp.domain.CSaleCustomer;
import cc.customer.saleHelp.domain.CsalePlan;
import cc.customer.saleHelp.services.CsalePlanServices;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.scripts.JS;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS,  rollbackFor = Exception.class)
public class CsalePlanServicesImpl extends BaseService<CsalePlan> implements CsalePlanServices {

    private static  final Logger logger = LoggerFactory.getLogger(CsalePlanServicesImpl.class);

    @Autowired
    private CsalePlanMapper csalePlanMapper;

    @Autowired
    private BigEmpServices bigEmpServices;
    @Autowired
    private BigEmpMapper bigEmpMapper;

    @Autowired
    private OnSchoolService onSchoolService;
    @Autowired
    private OnSchoolResourceMapper onSchoolResourceMapper;

    @Autowired
    private ExEmpServices exEmpServices;
    @Autowired
    private ExEmpMapper exEmpMapper;

    @Autowired
    private CustomeForMy customeForMy;

    @Autowired
    private MyCustomerMapper myCustomerMapper;

    @Autowired
    private AiEmpServices caiEmpMapper;

    @Autowired
    private CSaleCustomerMapper customerMapper;


    @Override
    @Transactional
    public ResponseBo saveCsalePlan(CsalePlan csalePlan)throws Exception {
        try {
            csalePlan.setcPlanCreatime(DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
            csalePlan.setcPlanIsdelete("0");
            csalePlan.setcPlanIsimp("0");
            csalePlan.setcPlanUuid(Utils.getUUID());
            int num = csalePlanMapper.insert(csalePlan);
            //获取定义的leixing
            List<String> listtype = Arrays.asList(csalePlan.getTypesAll().split(","));
            List<String> listUserUuid = Arrays.asList(csalePlan.getcPlanCusid().split(","));

            logger.error(listUserUuid.toString()+"---------------------");
            logger.error(listtype.toString()+"---------------------");

            /*List<String> bigEmp = new ArrayList<>();
            List<String> exEmp = new ArrayList<>();
            List<String> school = new ArrayList<>();
            List<String> myCustom = new ArrayList<>();
            List<String> aiEmp = new ArrayList<>();*/
            List<CSaleCustomer> clist = new ArrayList<>();
            CSaleCustomer saleCustomer = null;
            for (int i =0;i<listtype.size();i++){
                saleCustomer = new CSaleCustomer();
                saleCustomer.setCpPid(csalePlan.getcPlanUuid());
                saleCustomer.setCpStatus("1");
                saleCustomer.setCpCusid(listUserUuid.get(i));
                saleCustomer.setCpCreateId(csalePlan.getcPlanUserid());
                String phone = null;
                String name = null;
                if(Constant.ZIYUAN_TYPE_BIGENP.equals(listtype.get(i))){//大资源类型
                    Example example = new Example(BigEmp.class);
                    example.createCriteria().andEqualTo("bpUuid",listUserUuid.get(i));
                    BigEmp b = bigEmpMapper.selectByExample(example).get(0);
                    phone = b.getBpMobile();
                    name = b.getBpName();

                    saleCustomer.setCpLeixing(Constant.ZIYUAN_TYPE_BIGENP);
                }else if(Constant.ZIYUAN_TYPE_EXEMP.equals(listtype.get(i))){//推广资源
                    Example example1 = new Example(ExEmp.class);
                    example1.createCriteria().andEqualTo("cExUuid", listUserUuid.get(i));
                    ExEmp e = exEmpMapper.selectByExample(example1).get(0);
                    phone = e.getcExMobile();
                    name = e.getcExName();

                    saleCustomer.setCpLeixing(Constant.ZIYUAN_TYPE_EXEMP);
                }else if(Constant.ZIYUAN_TYPE_SCHOLLE.equals(listtype.get(i))){//网校资源
                    Example example2 = new Example(OnSchoolResource.class);
                    example2.createCriteria().andEqualTo("osUuid",listUserUuid.get(i));
                    OnSchoolResource  o= onSchoolResourceMapper.selectByExample(example2).get(0);
                    phone = o.getOsMobile();
                    name = o.getOsNickname();

                    saleCustomer.setCpLeixing(Constant.ZIYUAN_TYPE_SCHOLLE);
                }else if(Constant.ZIYUAN_TYPE_MINE.equals(listtype.get(i))){//我的客户资源
                    Example example3 = new Example(MyCustomer.class);
                    example3.createCriteria().andEqualTo("myCusUuid",listUserUuid.get(i));
                    MyCustomer m = myCustomerMapper.selectByExample(example3).get(0);
                    phone = m.getMyCusMobile();
                    name = m.getMyCusName();

                    saleCustomer.setCpLeixing(Constant.ZIYUAN_TYPE_MINE);
                }else if(Constant.ZIYUAN_TYPE_AI.equals(listtype.get(i))){//AI客户资源
                    Example example4 = new Example(CAiEmp.class);
                    example4.createCriteria().andEqualTo("aiRUuid", listUserUuid.get(i));
                    CAiEmp c = caiEmpMapper.selectByExample(example4).get(0);
                    phone = c.getAiMobile();
                    name = c.getAiName();

                    saleCustomer.setCpLeixing(Constant.ZIYUAN_TYPE_AI);
                }
                saleCustomer.setCpCusName(name);
                saleCustomer.setCpPhone(phone);
                customerMapper.insert(saleCustomer);
           }
            /*if (!bigEmp.isEmpty()){
                //更新 大资源的用户的销售计划
                logger.error("大资源-------"+bigEmp.toString());
                BigEmp bigEmp1 = new BigEmp();
                bigEmp1.setBpPlan("1");
                bigEmpServices.batchUpdate(bigEmp,"bpUuid",BigEmp.class,bigEmp1);

            }
            if(!exEmp.isEmpty()){
                //更新 推广资源的销售计划
                logger.error("推广-------"+exEmp.toString());
                ExEmp exEmp1 = new ExEmp();
                exEmp1.setcExPlan("1");
                exEmpServices.batchUpdate(exEmp,"cExUuid",ExEmp.class,exEmp1);
            }
            if(!school.isEmpty()){
                //更新 网校资源的销售计划
                logger.error("网校-------"+school.toString());
                OnSchoolResource onSchoolResource = new OnSchoolResource();
                onSchoolResource.setOsPlan("1");
                onSchoolService.batchUpdate(school,"osUuid",OnSchoolResource.class,onSchoolResource);
            }
            if(!myCustom.isEmpty()){
                //更新 我的客户资源的销售计划
                logger.error("我的-------"+myCustom.toString());
                MyCustomer myCustomer = new MyCustomer();
                myCustomer.setMyCusPlan("1");
                customeForMy.batchUpdate(myCustom,"myCusUuid",MyCustomer.class,myCustomer);
            }
            if (!aiEmp.isEmpty()){
                //更新 ai资源的销售计划
                logger.error("ai资源类型更新:"+aiEmp.toString());
                CAiEmp cAiEmp = new CAiEmp();
                cAiEmp.setAiPlan("1");
                caiEmpMapper.batchUpdate(aiEmp,"aiRUuid",CAiEmp.class,cAiEmp);
            }*/
            if (num > 0 ){
                return ResponseBo.ok(csalePlan);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新建个人计划失败："+e.getMessage());
            throw new RuntimeException();
        }
        return ResponseBo.error("新增销售计划失败");
    }

    @Override
    public ResponseBo selectAllMyCsalePlan(CsalePlan csalePlan) {
        try {
            Example example = new Example(CsalePlan.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("cPlanUserid",csalePlan.getcPlanUserid());
            criteria.andEqualTo("cPlanIsdelete","0");


            String now = DateUtil.getCurrentDate("yyyy-MM-dd");
            //今天
            if ("2".equals(csalePlan.getcPlanSelectCondition())){
                criteria.andBetween("cPlanTime",now+" 00:00:00",now+" 23:59:59").andEqualTo("cPlanIsimp","0");
            }else if ("3".equals(csalePlan.getcPlanSelectCondition())){
                //未来七天
                Date date = new Date();
                Date curent = DateUtil.addDays(date,7);
                String date7Day  = DateUtil.convert2String(curent,"yyyy-MM-dd");
                criteria.andBetween("cPlanTime",now+" 00:00:00",date7Day+" 23:59:59").andEqualTo("cPlanIsimp","0");
            }else if ("4".equals(csalePlan.getcPlanSelectCondition())){
                //已经过期的
                String nowday = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss");
                criteria.andBetween("cPlanTime","1991-04-28 00:00:00",nowday).andEqualTo("cPlanIsimp","0");
            }else{
                String  cplanIsImp = csalePlan.getcPlanSelectCondition(); //0,1
                if (!StringUtils.isEmpty(cplanIsImp)){
                    //未执行   //已经执行
                    criteria.andEqualTo("cPlanIsimp",cplanIsImp);
                }
            }
            if(!StringUtils.isEmpty(csalePlan.getcPlanType())){
                criteria.andEqualTo("cPlanType",csalePlan.getcPlanType());
            }
            example.setOrderByClause("c_plan_creatime desc");
            List<CsalePlan> list = this.selectByExample(example);

            if(list.size()>0){
                for(CsalePlan plan:list){
                    Example example1 = new Example(CSaleCustomer.class);
                    //已执行的个数
                    example1.createCriteria().andEqualTo("cpPid",plan.getcPlanUuid()).andEqualTo("cpStatus","2");
                    int numyi = customerMapper.selectByExample(example1).size();

                    //未执行的个数
                    Example example2 = new Example(CSaleCustomer.class);
                    example2.createCriteria().andEqualTo("cpPid",plan.getcPlanUuid()).andEqualTo("cpStatus","1");
                    int numwei = customerMapper.selectByExample(example2).size();
                    int all = numwei+numyi;
                    if(numyi==all){
                        plan.setcPlanIsimp("已执行");
                    }else if(numyi==0){
                        plan.setcPlanIsimp("未执行");
                    }else{

                        plan.setcPlanIsimp(numyi+"/"+all);
                    }
                }
            }


            return ResponseBo.ok(list);
        }catch (Exception e){
            logger.error("获取个人销售计划失败："+e.getMessage());
        }
        return ResponseBo.error(new ArrayList<CsalePlan>());
    }

    /**
     * app计划
     * @param csalePlan
     * @return
     */
    @Override
    public ResponseBo selectAppAMyCsalePlanDetail(CsalePlan csalePlan) {

        try {
            CsalePlan plan = csalePlanMapper.selectOne(csalePlan);

            List<String> PlanCusid = Arrays.asList(plan.getcPlanCusid().split(","));
            List<String> PlanCname = Arrays.asList(plan.getcPlanCname().split(","));



            return ResponseBo.ok(plan);
        }catch (Exception e){
            logger.error("获取销售计划详情失败："+e.getMessage());
        }
        return ResponseBo.error();
    }
    @Override
    public ResponseBo selectAMyCsalePlanDetail(CsalePlan csalePlan) {

        try {
            CsalePlan plan = csalePlanMapper.selectOne(csalePlan);
            return ResponseBo.ok(plan);
        }catch (Exception e){
            logger.error("获取销售计划详情失败："+e.getMessage());
        }
        return ResponseBo.error();
    }

    @Override
    public ResponseBo updateMyCsaleDetail(CsalePlan csalePlan) {
        try {
            this.updateNotNull(csalePlan);
            return  ResponseBo.ok("更新成功");
        }catch (Exception e){
            logger.error("修改计划失败"+e.getMessage());
        }
        return ResponseBo.error("更新失败");
    }

    @Override
    public ResponseBo selectSalePlanByUserUuid(String userUuid,String isImpl) {

        try {
            Example example = new Example(CsalePlan.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andLike("cPlanCusid","%"+userUuid+"%").andEqualTo("cPlanIsdelete","0");
            if (!StringUtils.isEmpty(isImpl)){
                criteria.andEqualTo("cPlanIsimp",isImpl);
            }
            List<CsalePlan> list = this.selectByExample(example);
            return ResponseBo.ok(list);
        }catch (Exception e){
            logger.error("根据客户的uuid 加载客户销售计划失败");
        }
        return ResponseBo.error();
    }

    @Override
    @Transactional
    public ResponseBo deleteSaclePlanUserUuid(String palnId, String userUuid,String types) {
        try {
            //先查出来模板当前使用的客户
            CsalePlan csalePlan = this.selectByKey(Integer.valueOf(palnId));
            //找出当前的使用的客户
            String cusid = csalePlan.getcPlanCusid();
            String cusname = csalePlan.getcPlanCname();
            if (!StringUtils.isEmpty(cusid) && !StringUtils.isEmpty(cusname)){
                List<String> listArr = Arrays.asList(cusid.split(","));
                List<String> listReal = new ArrayList<>(listArr);

                List<String> listArrName = Arrays.asList(cusname.split(","));
                List<String> listRealName = new ArrayList<>(listArrName);
                for (int i=0;i<listReal.size();i++){
                    if (listReal.get(i).equals(userUuid)){
                        listReal.remove(i);
                        listRealName.remove(i);
                        break;
                    }
                }
                String l = StringUtils.join(listReal.toArray(), ",");
                String n = StringUtils.join(listRealName.toArray(), ",");
                csalePlan.setcPlanCusid(l);
                csalePlan.setcPlanCname(n);
            }
            if (!StringUtils.isEmpty(csalePlan.getcPlanCusid())){
                this.updateNotNull(csalePlan);
            }else{
                csalePlan.setcPlanIsdelete("1");
                this.updateNotNull(csalePlan);
            }
            /**查询当前用户是否还有使用的销售计划**/
            Example example = new Example(CsalePlan.class);
            example.createCriteria().andLike("cPlanCusid","%"+userUuid+"%").andEqualTo("cPlanIsdelete","0");
            List<CsalePlan> listAll = this.selectByExample(example);
            if (listAll.isEmpty()){
                //更新原有的数据
                switch (types){
                    case Constant.ZIYUAN_TYPE_EXEMP: //推广资源
                        exEmpMapper.changeExempCusPlan(userUuid);
                        break;
                    case Constant.ZIYUAN_TYPE_SCHOLLE: //网校资源
                        onSchoolResourceMapper.changeSchoolCusPlan(userUuid);
                        break;
                    case Constant.ZIYUAN_TYPE_BIGENP:  //大资源类型
                        bigEmpMapper.changeBigCusPlan(userUuid);
                        break;
                    case Constant.ZIYUAN_TYPE_MINE : //个人资源
                        myCustomerMapper.changeMyCusCusPlan(userUuid);
                        break;
                        default:
                }
            }

            return ResponseBo.ok();
        }catch (Exception e){
            logger.error("删除客户自己的销售计划失败 :"+e.getMessage());
        }
        return ResponseBo.error();
    }

    /**查计划详情*/
    @Override
    public ResponseBo selectPlanCusList(CsalePlan csalePlan){
        try {
            CsalePlan sc = this.selectByKey(csalePlan);
            return ResponseBo.ok("",sc);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseBo.error();
    }

    /**初始化左侧菜单的数量*/
    @Override
    public ResponseBo getTypeNum(){
        try {
            String now = DateUtil.getCurrentDate("yyyy-MM-dd");
            //今天
            Example example = new Example(CsalePlan.class);
            example.createCriteria().andBetween("cPlanTime",now+" 00:00:00",now+" 23:59:59").andEqualTo("cPlanIsimp","0");
            int today = this.selectByExample(example).size();

            //未来七天
            Example example1 = new Example(CsalePlan.class);
            Date date = new Date();
            Date curent = DateUtil.addDays(date,7);
            String date7Day  = DateUtil.convert2String(curent,"yyyy-MM-dd");
            example1.createCriteria().andBetween("cPlanTime",now+" 00:00:00",date7Day+" 23:59:59").andEqualTo("cPlanIsimp","0");
            int seven = this.selectByExample(example1).size();

            //已经过期的
            Example example2 = new Example(CsalePlan.class);
            String nowday = DateUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss");
            example2.createCriteria().andBetween("cPlanTime","1991-04-28 00:00:00",nowday).andEqualTo("cPlanIsimp","0");
            int already = this.selectByExample(example2).size();

            //未执行
            Example example3 = new Example(CsalePlan.class);
            example3.createCriteria().andEqualTo("cPlanIsimp","0");
            int wei = this.selectByExample(example3).size();

            //已经执行
            Example example4 = new Example(CsalePlan.class);
            example4.createCriteria().andEqualTo("cPlanIsimp","1");
            int yi = this.selectByExample(example4).size();

            JSONObject json = new JSONObject();
            json.put("today",today);
            json.put("seven",seven);
            json.put("already",already);
            json.put("wei",wei);json.put("yi",yi);
            return ResponseBo.ok("",json);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseBo.error();
    }


}


